package com.lxd.api.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.pool.ConnFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author Dongdong
 * @注释  设置mq的一些机制，如设置RabbitTemplate的confirm&return机制
 */
@Configuration
@Slf4j
public class RabbitTemplateConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        //2.将connectionFactory舍之道rabbitTemp对象中
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //3.设置confirm 回调
        rabbitTemplate.setConfirmCallback(confirmCallback());
        //4.设置return机制
        rabbitTemplate.setReturnCallback(returnCallback());
        //5.找不到合适队列，将消息返回给生产者
//        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }
    // confirm: 保证消息发送到交换机
    public RabbitTemplate.ConfirmCallback confirmCallback(){
        return new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack){
                    log.info("【接口模块-发送消息】消息已经发送到交换机");
                }else {
                    log.error("【接口模块-发送消息】消息未发送到交换机，correlationData={}，cause={}",correlationData,cause);
                }

            }
        };
    }
    //return：保证消息到队列
    public RabbitTemplate.ReturnCallback returnCallback(){
        return new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode
                    , String replyText, String exchange, String routingKey) {
                log.error("【接口模块-发送消息】 消息没有路由到指定的Queue。 message = {},exchange = {},routingKey = {}"
                ,new String(message.getBody()),exchange,routingKey);

            }
        };
    }
}
